package com.mate.cloud.auth.service.impl;

import com.mate.cloud.auth.constant.LoginUserExceptionCodeEnum;
import com.mate.cloud.auth.entity.MateUser;
import com.mate.cloud.auth.entity.UmsUser;
import com.mate.cloud.auth.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @description: java类作用描述
 * @author: MI
 * @email: 448341911@qq.com
 * @createTime: 2025/2/3 16:58
 * @updateUser: MI
 * @updateTime: 2025/2/3 16:58
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    // 用户服务
    private UserService userService;

    public CustomUserDetailsService(UserService userService) {
        this.userService = userService;
    }

    /**
     * @param username 前端登录时提交的用户名
     * @return 用户的认证信息，要求必须为UserDetails接口的实现类
     * @throws UsernameNotFoundException 用户名没有找到时的异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("loadUserByUsername(String username) :: {}", username);
        final UmsUser umsUser = userService.selectByUsername(username);
        if (umsUser == null) {
            throw new UsernameNotFoundException(LoginUserExceptionCodeEnum.USER_NOT_FOUND_ERROR.getMassage());
        }
        // 创建 UserDetails 对象
        return new MateUser(umsUser,AuthorityUtils.createAuthorityList());
    }

//    private Collection<? extends GrantedAuthority> getAuthorities(
//            Collection<Role> roles) {
//        List<GrantedAuthority> authorities
//                = new ArrayList<>();
//        for (Role role : roles) {
////            authorities.add(new SimpleGrantedAuthority(role.getName()));
//            role.getPermissions().stream()
//                    .map(p -> new SimpleGrantedAuthority(p.getName()))
//                    .forEach(authorities::add);
//        }
//
//        return authorities;
//    }

}
